<?php
/**
 * 会员信息
 * @return
 * @author yuncran@126.com
 */

namespace app\api\controller;

use app\BaseController;
use app\CacheKey;
use app\FieldKey;
use app\model\ConfigModel;
use app\model\LevelModel;
use app\model\TrendsCommentModel;
use app\model\TrendsMagModel;
use app\model\TrendsModel;
use app\model\TrendsReportModel;
use app\model\TrendsUserLikeModel;
use app\model\UserBlacklistModel;
use app\model\UserCensusCountModel;
use app\model\UserComeVisitModel;
use app\model\UserFollowModel;
use app\model\UserImageModel;
use app\model\UserModel;
use app\services\SendMessageServices;
use app\services\UserService;
use think\facade\Cache;
use think\facade\Db;

class UserAuth extends BaseController
{

    public function getUser()
    {
        $data = $this->request->param();
        $user = UserModel::field(FieldKey::get_user_field)->with(['getLevelName'])->find($data['user_id']);
        if (!$user) {
            return $this->renderError(lang('用户不存在'));
        }
        return $this->renderSuccess($user, 'ok');
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author yuncran@126.com
     */
    public function getUserInfo()
    {
        $param = $this->request->param();
        $user_id = !empty($param) ? $param['user_id'] : $this->uid;
        if (!empty($param['user_id'])) {
            //查看黑名单
            $userBlacklist = UserBlacklistModel::where(['user_id' => $param['user_id'], 'to_user_id' => $this->uid])->find();
            if ($userBlacklist) return $this->renderError(lang('您未权限查看该会员信息'));
        }
        $user = UserModel::field(FieldKey::get_user_field)->with(['getLevelName'])->find($user_id);
        if (!$user) {
            return $this->renderError(lang('用户不存在'));
        }
        $user->level_name = LevelModel::where('id',$user['level'])->value(field('title'));
        $user->tags = empty($user->tags) ? [] : explode(',', $user->tags);
        //是否关注
        $map = [['user_id', '=', $this->uid], ['to_user_id', '=', $user_id]];
        $is_follow = UserFollowModel::where($map)->find();
        $user->is_follow = empty($is_follow) ? 2 : 1;
        $user->expire_time  = !empty($user->expire_time) ? date('Y-m-d',strtotime($user->expire_time))  : '';
        //新增访问记录
        $userComeMe = UserComeVisitModel::where(['user_id' => $this->uid, 'to_user_id' => $user_id])->find();
        if (empty($userComeMe) && $this->uid != $user_id) {
            UserComeVisitModel::saveIn($this->uid, $user_id);
        }
        return $this->renderSuccess($user, lang('查询成功'));
    }


    // 修改用户信息 || 绑定邮箱
    public function updateUserInfo()
    {
        try {
            $data = $this->request->param();
            $user = UserModel::find($this->uid);
            if (!$user) {
                return $this->renderError(lang('用户不存在'));
            }

            if (isset($data['tags'])) {
                if (!empty($data['tags'])) {
                    $res = explode(',', $data['tags']);
                    if (count($res) > 4) {
                        return $this->renderError(lang('标签最多设置4个'));
                    }
                }
            }

            if (isset($data['nickname'])) {
                $userInfo = UserModel::where(['nickname' => $data['nickname']])
                    ->withoutField('joinip,login_count,update_time,create_time')->find();
                if ($userInfo) {
                    return $this->renderError(lang('您的账号已重复'));
                }
            }

            $user->nickname = isset($data['nickname']) ? $data['nickname'] : $user['nickname'];
            $user->email = isset($data['email']) ? $data['email'] : $user['email'];
            $user->bio = isset($data['bio']) ? $data['bio'] : $user['bio'];
            $user->gender = isset($data['gender']) ? $data['gender'] : $user['gender'];
            $user->country = isset($data['country']) ? $data['country'] : $user['country'];
            $user->city = isset($data['city']) ? $data['city'] : $user['city'];
            $user->area = isset($data['area']) ? $data['area'] : $user['area'];
            $user->tags = isset($data['tags']) ? $data['tags'] : $user['tags'];
            $user->avatar = isset($data['avatar']) ? $data['avatar'] : $user['avatar'];
//            $user->account = pinyin_sentence($data['nickname']);
            $user->save();
            return $this->renderSuccess($data, lang('修改成功'));
        } catch (\Exception $e) {
            return $this->renderError($e->getMessage());
        }
    }

    /**
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function resetPassword()
    {
        $data = $this->request->param();
        $message = array(
//            'originalPassword.require' => lang('密码必填'),
            'password.min' => lang('密码长度不能小于6个字符'),
            'password.max' => lang('密码长度在6~15个字符'),
            'password_confirm.require' => lang('密码必填'),
            'email.email' => lang('邮箱格式不正确'),
            'email.require' => lang('邮箱必填'),
            'code.require' => lang('code必填'),
        );
        $validate = new \think\Validate();
        $check = $validate->message($message)->check($data,
            [
                'password_confirm' => 'require', 'password' => 'require|min:6|max:15',
            ]
        );
        $user = UserModel::where(['email' => $data['email']])->find();

        if (empty($user)) return $this->renderError(lang('未找到注册会员'));

        if (!$check) return $this->renderError($validate->getError());
        if ($data['password'] != $data['password_confirm']) return $this->renderError(lang('两次密码输入的不一致！'));
        if (!isPasswordSimple($data['password'])) return $this->renderError(lang('您输入的密码太简单了！'));
        $key = 'email' . $data['email'];
        $code = Cache::get($key);
        if ($code != $data['email']) {
            return $this->renderError(lang('code错误'));
        }
        try {
            $password = $this->request->param('password', '');
            $salt = \utils\Str::random(4);
            $new_password = password_hash_tp($password, $salt);
            UserModel::where(['email' => $data['email']])->update(
                [
                    'password' => $new_password,
                    'salt' => $salt,
                    'updatetime' => time(),
                ]
            );
            return $this->renderSuccess(lang('修改成功'));
        } catch (\Exception $e) {
            return $this->renderError(lang('修改失败'));
        }
    }


    /**
     * 会员修改密码
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function editPassword()
    {
        $user_id = $this->userInfo['user_id'];
        $user = UserModel::find($user_id);
        if (!$user) return $this->renderError(lang('用户不存在'));
        $data = $this->request->param();
        $message = array(
//            'originalPassword.require' => lang('密码必填'),
            'password.min' => lang('密码长度不能小于6个字符'),
            'password.max' => lang('密码长度在6~15个字符'),
            'password_confirm.require' => lang('密码必填'),
        );
        $validate = new \think\Validate();
        $check = $validate->message($message)->check($data,
            [
//                'originalPassword' => 'require',
                'password_confirm' => 'require', 'password' => 'require|min:6|max:15',
            ]
        );

        if (!$check) return $this->renderError($validate->getError());
        if ($data['password'] != $data['password_confirm']) return $this->renderError(lang('两次密码输入的不一致！'));
        if (!isPasswordSimple($data['password'])) return $this->renderError(lang('您输入的密码太简单了！'));

        try {
            if ($user->password != password_hash_tp($data['originalPassword'], $user->salt)) {
                return $this->renderError(lang('原始密码不正确'));
            }
            if ($user->password == password_hash_tp($data['password'], $user->salt)) {
                return $this->renderError(lang('新密码与旧密码一致'));
            }
            $password = $this->request->param('password', '');
            if ($password) {
                $salt = $user->salt;
                $user->password = password_hash_tp($password, $salt);
            }
            $user->save();
            return $this->renderSuccess(lang('修改成功'));
        } catch (\Exception $e) {
            return $this->renderError(lang('修改失败'));
        }
    }

    /**
     * 添加会员相册
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author yuncran@126.com
     */
    public function addUserPhoto()
    {
        $param = $this->request->param(['image' => '']);
        $data = array(
            'user_id' => $this->uid,
            'image' => $param['image'],
            'createtime' => time(),
            'updatetime' => time(),
        );
        $user_photo = UserImageModel::create($data);
        return $this->renderSuccess($user_photo);
    }

    /**
     * 动态图片集
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function getTrendsImages()
    {
        $param = $this->request->param(['user_id' => '']);

        $data = Db::name('trends')->where('image', '<>', '')->where('user_id', $param['user_id'])
            ->field(['id', 'image', 'create_time', 'user_id'])
            ->paginate()->each(function ($item) {
                $item['image'] = !empty($item['image']) ? explode(',', $item['image']) : '';
                return $item;
            });
        $total = 0;
        $image = Db::name('trends')->where('user_id', $param['user_id'])->where('image', '<>', '')->column('image');
        if (!empty($image)) {
            foreach ($image as $value) {
                $image = !empty($value) ? explode(',', $value) : '';
                $total += !empty($image) ? count($image) : 0;
            }
        }
        return $this->renderSuccess(['total_count' => $total, 'list' => $data]);
    }

    /**
     * 获取会员相册
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author yuncran@126.com
     */
    public function getUserPhoto()
    {
        $param = $this->request->param(['user_id' => '']);
        $where[] = empty($param['user_id']) ? ['user_id', '=', $this->uid] : ['user_id', '=', $param['user_id']];
        $user_photo = UserImageModel::field(['id', 'user_id', 'image', 'createtime'])->where($where)
            ->paginate()->each(function ($item) {
                return $item;
            });;
        $total = UserImageModel::where($where)->count();
        return $this->renderSuccess(['total_count' => $total, 'list' => $user_photo]);
    }

    /**
     * 会员删除相册
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function delUserPhoto()
    {
        $photo_ids = $this->request->param('photo_id');
        $user_photo = UserImageModel::when($photo_ids, function ($query) use ($photo_ids) {
            if (is_array($photo_ids)) {
                $query->whereIn('id', $photo_ids);
            } else {
                $query->where('id', $photo_ids);
            }
        })->delete();
        return $this->renderSuccess($user_photo);
    }

    /**
     * 会员来访记录
     * @return void
     * @author yuncran@126.com
     */
    public function getUserComeVisitList()
    {
        $user_come_visit_list = UserComeVisitModel::field(['id', 'user_id', 'to_user_id', 'create_time'])->with(['getUser'])
            ->where(['to_user_id' => $this->uid])
            ->paginate()->each(function ($item) {
                return $item;
            });
        return $this->renderSuccess($user_come_visit_list);
    }

    /**
     * 清空来访记录
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author yuncran@126.com
     */
    public function userClearUserComeVisit()
    {
        $user_come_visit_list = UserComeVisitModel::where(['to_user_id' => $this->uid])->delete();
        return $this->renderSuccess($user_come_visit_list);
    }

    /**
     * 获取会员动态
     * @return void
     * @author yuncran@126.com
     */
    public function getUserTrends()
    {
        $param = $this->request->param(['limit' => '15', 'type' => 1, 'to_user_id' => 0]);
        $user_trends = TrendsModel::alias('trends')
            ->leftJoin('fa_user user', 'user.id = trends.user_id')
//            ->where(['trends.frame_status'=>1,'trends.status'=>1])
            ->when($param, function ($query) use ($param) {
                if ($param['type'] == 2) {
                    $user_follow = UserFollowModel::where('user_id', $this->uid)->column('to_user_id');
                    $model = $query->where('trends.user_id', 'in', $user_follow)->where(['trends.frame_status'=>1,'trends.status'=>1]);
                } elseif ($param['type'] == 3) {
                    $model = $query->where(['trends.is_recommend' => 1])->where(['trends.frame_status'=>1,'trends.status'=>1]);
                } elseif ($param['type'] == 4) {
                    $model = $query->where(['trends.user_id' => $this->uid]);
                } elseif ($param['type'] == 5) {
                    $model = $query->where(['trends.user_id' => $param['to_user_id']])->where(['trends.frame_status'=>1,'trends.status'=>1]);
                } else {
//                    $model = $query->where('user.gender', '<>', UserModel::where('id', $this->uid)->value('gender'))
                    $model = $query->where(['trends.frame_status'=>1,'trends.status'=>1]);
                }
                return $model;
            })->field(['trends.*'])
            ->order(['trends.id' => 'DESC'])
            ->paginate($param['limit'])->each(function ($item) {
                $mention = Db::name('trends_mag')->where('trends_ids', $item['id'])->field('users')
                    ->append(['user_nickname'])
                    ->withAttr('user_nickname', function ($value, $data) {
                        return UserModel::where(['id' => $data['users']])->value('nickname');
                    })->select();
                $item['mention'] = $mention;

                /** 分享的人 */
                $trends_user_like = Db::name('trends_user_like')->where('status', 3)->where('share_trends_id', $item['id'])->find();
                if (!empty($trends_user_like)) {
                    $item['user_share'] = Db::name('user')->where('id', $trends_user_like['to_user_id'])->field('id,nickname')->find();
                } else {
                    $item['user_share'] = '';
                }
                //是否评论
                $retWhere = [['user_id', '=', $this->uid], ['trends_id', '=', $item['id']]];
                $item['is_comment_status'] = empty(TrendsCommentModel::where($retWhere)->find()) ? 0 : 1;
                //是否分享
                $item['is_share_status'] = empty(TrendsUserLikeModel::getIsStatus($this->uid, 3, $item['id'])) ? 0 : 1;
                //是否收藏
                $item['is_collect_status'] = empty(TrendsUserLikeModel::getIsStatus($this->uid, 4, $item['id'])) ? 0 : 1;
                //是否点赞
                $item['is_like_status'] = empty(TrendsUserLikeModel::getIsStatus($this->uid, 1, $item['id'])) ? 0 : 1;

                $item['image'] = !empty($item['image']) ? explode(',', $item['image']) : '';
                $item['video'] = !empty($item['video']) ? explode(',', $item['video']) : '';

                return $item;
            });
        return $this->renderSuccess($user_trends);
    }


    /**
     * 查看动态详情
     * @return void
     * @author yuncran@126.com
     */
    public function trendsDetails()
    {
        $param = $this->request->param(['trends_id' => '', 'to_user_id' => '']);
        if (empty($param['trends_id'])) return $this->renderError(lang('缺少参数'));
        $data = TrendsModel::where('id', $param['trends_id'])->find();
        //是否点赞
        $data['is_like_status'] = empty(TrendsUserLikeModel::getIsStatus($this->uid, 1, $param['trends_id'])) ? 0 : 1;
        //是否分享
        $data['is_share_status'] = empty(TrendsUserLikeModel::getIsStatus($this->uid, 3, $param['trends_id'])) ? 0 : 1;
        //收藏
        $data['is_collect_status'] = empty(TrendsUserLikeModel::getIsStatus($this->uid, 4, $param['trends_id'])) ? 0 : 1;
        //是否评论
        $retWhere = [['user_id', '=', $this->uid], ['trends_id', '=', $param['trends_id']]];
        $data['is_comment_status'] = empty(TrendsCommentModel::where($retWhere)->find()) ? 0 : 1;
        $data['image'] = empty($data['image']) ? '' : explode(',', $data['image']);
        $data['video'] = empty($data['video']) ? '' : explode(',', $data['video']);
        //是否关注
        $map = [['user_id', '=', $this->uid], ['to_user_id', '=', $data['user_id']]];
        $is_follow = UserFollowModel::where($map)->find();
        $data['is_follow'] = empty($is_follow) ? 2 : 1;
        return $this->renderSuccess($data, lang('操作成功'));
    }

    /**
     * 会员发布动态
     * @return void
     * @author yuncran@126.com
     */
    public function userAddTrends()
    {
        $userInfo = UserModel::getUserInfo(['id' => $this->uid]);
        $param = $this->request->param([
            'user_id' => $this->uid,
            'status' => 0,
            'create_time' => date('Y-m-d H:i:s', time()),
            'title' => '',
            'content' => '',
            'type' => '',
            'image' => '',
            'video' => '',
            'remarks' => '',
            'merchant_id' => $this->merchantId,
        ]);
        $param['image'] = is_array($param['image']) ? implode(',', $param['image']) : '';
        $param['video'] = is_array($param['video']) ? implode(',', $param['video']) : '';
        try {
            $add_trends = TrendsModel::create($param);
            $users = $this->request->param('user');
            if (!empty($users) && $add_trends) {
                /** 会员通知 */
                $use_id = $add_trends->id;
                foreach ($users as $val) {
                    (new \app\services\SendMessageServices())->checkUserSendMessage($this->uid, $val, 'trends_mag', $use_id);
                }
            }
            /** 增加发布动态数量 */
            UserService::UserCensusCount($this->uid, 'add', 'user_trends_count');
        } catch (\Throwable $throwable) {
            return $this->renderError('error', ['message' => $throwable->getMessage()]);
        }
        return $this->renderSuccess($add_trends);
    }

    /**
     * @我
     * @return void
     * @author yuncran@126.com
     */
    public function userAddAssociation()
    {
        $param = $this->request->param();
        $shape = array(
            'user_id' => $this->uid, 'trends_ids' => 0, 'users' => $param['friend_id'],
            'is_read' => 0,
            'create_time' => date('Y-m-d H:i:s', time()),
            'type' => 1,
        );
        TrendsMagModel::create($shape);
        SendMessageServices::userSend($param['friend_id'], 'trends', '@我的');
        return $this->renderSuccess([], lang('@TA成功'));
    }

    /**
     * 清空内容 @我的
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function userAssociationDel()
    {
        TrendsMagModel::where('users', $this->uid)->delete();
        return $this->renderSuccess([], lang('操作成功'));
    }

    /**
     * 删除动态
     * @return void
     * @author yuncran@126.com
     */
    public function userDelTrends()
    {
        $trends = $this->request->param(['trends_id' => '']);
        if (!TrendsModel::where(['id' => $trends['trends_id']])->delete()) {
            return $this->renderError('error', []);
        }
        UserCensusCountModel::where('user_id', $this->uid)->dec('user_trends_count', 1)->update();
        event('Trends', $trends);
        return $this->renderSuccess([], lang('操作成功'));
    }

    /**
     * 动态举报
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function trendsReport()
    {
        $param = $this->request->param([
            'user_id' => $this->uid,
            'to_user_id' => '',
            'trends_id' => '',
            'content' => '',
        ]);
        $validate = new \think\Validate();
        $message = array(
            'user_id.require' => lang('会员ID不能为空'),
            'to_user_id.require' => lang('被举报人to_user_id不能为空'),
            'trends_id.require' => lang('动态trends_id不能为空'),
            'content.require' => lang('举报内容不能为空'),
        );
        $check = $validate->message($message)->check($param,
            [
                'user_id' => 'require',
                'to_user_id' => 'require',
                'trends_id' => 'require',
                'content' => 'require',
            ]
        );
        if (!$check) {
            return json(['code' => 0, 'msg' => $validate->getError(), 'data' => []]);
        }
        $trendsReport = TrendsReportModel::create($param);
        return $this->renderSuccess($trendsReport);
    }

    /**
     * 会员加入黑名单
     * @return void
     * @author yuncran@126.com
     */
    public function addUserBlack()
    {
        $param = $this->request->param([
            'user_id' => $this->uid,
            'to_user_id' => '',
        ]);
        $validate = new \think\Validate();
        $message = array(
            'user_id.require' => lang('会员ID不能为空'),
            'to_user_id.require' => lang('黑名单人to_user_id不能为空'),
        );
        $check = $validate->message($message)->check($param,
            [
                'user_id' => 'require',
                'to_user_id' => 'require',
            ]
        );
        if (!$check) {
            return json(['code' => 0, 'msg' => $validate->getError(), 'data' => []]);
        }
        $this->startTrans();
        try {
            $userBlack = UserBlacklistModel::where($param)->find();
            if ($userBlack) {
                return $this->renderError(lang('您已添加过了、不能重复添加'));
            }
            $addUserBlack = UserService::addUserBlack($param);
            //查找黑名单
            UserFollowModel::where('user_id', $this->uid)->where('to_user_id', $param['to_user_id'])->delete();
            $this->commit();
        } catch (\Throwable $exception) {
            $this->rollback();
            return $this->renderError(lang('操作失败'));
        }

        return $this->renderSuccess($addUserBlack);
    }


    /**
     * 获取会员黑名单
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author yuncran@126.com
     */
    public function getUserBlackList()
    {
        $param = $this->request->param(['user_id' => $this->uid, 'keywords' => '','limit'=>8]);
        $getUserBlackList = UserService::getUserBlackList($this->uid, $param);
        return $this->renderSuccess($getUserBlackList);
    }

    /**
     * 移除黑名单
     * @return void
     * @author yuncran@126.com
     */
    public function userBlackDel()
    {
        $param = $this->request->param(['user_id' => $this->uid, 'id' => '']);
        $validate = new \think\Validate();
        $message = array(
            'user_id.require' => lang('会员ID不能为空'),
            'user_id.gt' => lang('会员ID未找到'),
            'id.require' => lang('ID不能为空'),
        );
        $check = $validate->message($message)->check($param,
            [
                'user_id' => 'require|gt:0',
                'id' => 'require',
            ]
        );
        if (!$check) return json(['code' => 0, 'msg' => $validate->getError(), 'data' => []]);

        $getUserBlackList = UserService::userBlackDel($param);
        if (!$getUserBlackList) return json(['code' => 0, 'msg' => lang('操作失败'), 'data' => []]);
        return $this->renderSuccess($getUserBlackList);
    }

    /**语言翻译
     * @return void
     * @author yuncran@126.com
     */
    public function render()
    {
        $url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        $app_id = "20200909000562012";
        $sec_key = "Kzfmnc9regRZGOV2yQag";
        $param = $this->request->param(['string' => '', 'language_type' => '']);
        if (empty($param['string'])) return $this->renderError(lang('您选择的图片或视频不能进行翻译'));
        if ($param['language_type'] == 'zh-tw') {
            $to = 'cht';
        } elseif ($param['language_type'] == 'en-us') {
            $to = 'en';
        } elseif ($param['language_type'] == 'ja-jp') {
            $to = 'jp';
        } elseif ($param['language_type'] == 'ko-kr') {
            $to = 'kor';
        } else {
            $to = 'zh';
        }
        $user = UserModel::getUserInfoFind(['id' => $this->uid], ['id', 'money', 'render']);
        $configValue = ConfigModel::where(['id' => 24])->value('value');
        if ($user['render'] < $configValue) {
            return $this->renderError(lang('您的翻译包余额不足、请充值'));
        }

        $args = [
            'q' => $param['string'],
            'appid' => $app_id,
            'salt' => rand(16680, 99999),
            'from' => 'auto',
            'to' => $to,
        ];
        $args['sign'] = $this->buildsign($param['string'], $app_id, $args['salt'], $sec_key);
        try {
            $queryUrl = $url . '?' . http_build_query($args, '&');
            $client = new \GuzzleHttp\Client();
            $response = $client->request('POST', $queryUrl);
            $ret = json_decode($response->getBody(), true);
            if (isset($ret['error_code'])) {
                return $this->renderError(lang(config('httpmsg')[$ret['error_code']]));
            }

            UserModel::minusUserDec($this->uid, 'render', $configValue);
            event('UserMoney', ['user_id' => $this->uid, 'money' => $configValue, 'before' => $user['render'],
                'after' => bcsub($user['render'], $configValue, 2), 'type' => 3,
            ]);
        } catch (\Throwable $throwable) {
            return $this->renderError(lang('翻译失败'));
        }
        return $this->renderSuccess($ret['trans_result'], 'success');
    }

    /**
     * 百度翻译加密
     * @param $string
     * @param $appID
     * @param $salt
     * @param $seckey
     * @return string
     * @author yuncran@126.com
     */
    private function buildsign($string, $appID, $salt, $seckey)
    {
        $str = $appID . $string . $salt . $seckey;
        return md5($str);
    }

}